from lawoffice import settings
from redis import Redis
from wechatpy import WeChatClient
from wechatpy.session.redisstorage import RedisStorage
from wxchat.models import WxUserInfo

redis_client = Redis.from_url(settings.REDIS_URL)
session_interface = RedisStorage(
    redis_client,
    prefix="case"
)


def get_wechat_client():
    """
    创建微信客户端对象
    :return:
    """
    client = WeChatClient(settings.WECHAT_APPID, settings.WECHAT_SECRET, session=session_interface)
    return client

# H8w6aWglGESFCiP4Uic1NcbMj63HPbKcgkNayxZjvcI 案件进度提醒
# {{first.DATA}}
# 案件名称：{{keyword1.DATA}}
# 办理律师：{{keyword2.DATA}}
# 当前进度：{{keyword3.DATA}}
# {{remark.DATA}}


def send_case_progress_to_client(**data):
    """充电开始提醒"""
    template = 'H8w6aWglGESFCiP4Uic1NcbMj63HPbKcgkNayxZjvcI'

    color = "#173177"
    send_data = {
        'first': {
            "value": '您的案件有新的进度',
            "color": color,
        },
        "keyword1": {

           "value": data.get("reason", None) or "",
           "color": color,
        },
        "keyword2": {
           "value": data.get("lawyer", None) or "",
           "color": color,
        },
        "keyword3": {
            "value": data.get("progress", None) or "",
            "color": color
        },
        "remark": {
           "value": "{},电话:{}".format(data.get("office_name", ""), data.get("telephone", "")),
           "color": "#f56c6c",
        }
    }
    client = get_wechat_client()
    openids = data.get("openids")

    for openid in openids:
        user = WxUserInfo.objects.filter(openid=openid).first()
        if user and user.subscribe == 1:
            client.message.send_template(user_id=openid, template_id=template, url=None, data=send_data)

